import {
  StyleSheet,
  View,
  Text,
  Pressable,
  TextInput,
  Animated,
  Image,
  StatusBar,
  ScrollView,
} from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { flexCol } from '../assets/style/common'
import { LinearGradient } from 'expo-linear-gradient'
import {
  useRef,
  useState,
  forwardRef,
  useImperativeHandle,
  useMemo,
} from 'react'
import Price from '../component/price'
import userCartContext from '../context/userCartContext'
import { useCardAnimation } from '@react-navigation/stack'
import { observer } from 'mobx-react-lite'
import { useStore } from '../store'

export default observer(function GoodParams({ navigation }: any) {
  const scrollY = useRef(new Animated.Value(0)).current
  const { variableStore } = useStore()
  const { current } = useCardAnimation()
  const goodNumRef = useRef<any>(null)
  const borderRadius = scrollY.interpolate({
    inputRange: [0, 24],
    outputRange: [12, 0],
    extrapolate: 'clamp',
  })
  const { dispatch: cartDispatch } = userCartContext()
  const attributes = [
    {
      id: 1,
      tit: '宫崎骏的夏天a',
      cover: require('../assets/images/good_d_c1.jpg'),
    },
    {
      id: 2,
      tit: '宫崎骏的夏天b',
      cover: require('../assets/images/good_d_c2.jpg'),
    },
    {
      id: 3,
      tit: '宫崎骏的夏天c',
      cover: require('../assets/images/good_d_c3.jpg'),
    },
    {
      id: 4,
      tit: '宫崎骏的夏天d',
      cover: require('../assets/images/good_d_c1.jpg'),
    },
    {
      id: 5,
      tit: '宫崎骏的夏天e',
      cover: require('../assets/images/good_d_c2.jpg'),
    },
  ]
  const attributes2 = [
    { id: 1, tit: '50*50' },
    { id: 2, tit: '60*60' },
    { id: 3, tit: '70*70' },
    { id: 4, tit: '80*780' },
  ]
  const [attrObj, setAttr] = useState({
    attr: 0,
    attr2: 0,
  })

  function onSetAttrs(key: 'attr' | 'attr2', value: number) {
    setAttr(
      Object.assign({}, attrObj, { [key]: attrObj[key] === value ? 0 : value }),
    )
  }
  function goCart() {
    const find1 = attributes.find(item => item.id === attrObj.attr)
    const find2 = attributes2.find(item => item.id === attrObj.attr2)
    if (!find1) {
      setModelStatus('请选择颜色分类')
      return
    }
    if (!find2) {
      setModelStatus('请选择尺寸')
      return
    }
    cartDispatch({
      type: 'addGoods',
      good: {
        id: 11,
        title: '宫崎骏的夏天',
        cId: 3,
        count: goodNumRef.current?.getValue(),
        price: 132,
        sale: 1000,
        type: find1.tit + ',' + find2.tit,
        cover: find1.cover,
        choosed: false,
      },
    })
    setModelStatus('已经加入购物车成功')
  }
  function setModelStatus(title: string) {
    navigation.navigate('Model', {
      type: 'info',
      message: title,
    })
  }
  function goBack() {
    navigation.goBack()
  }
  const height = useMemo(() => {
    return variableStore.screen.height * 0.8
  }, [])
  return (
    <Pressable onPress={goBack} style={styles.goodParams}>
      <StatusBar barStyle="light-content" />
      <Animated.View
        style={[
          flexCol(styles.container),
          {
            transform: [
              {
                translateY: current.progress.interpolate({
                  inputRange: [0, 1],
                  outputRange: [height, 0],
                  extrapolate: 'clamp',
                }),
              },
            ],
          },
        ]}
      >
        <Pressable>
          <View style={flexCol(styles.header)}>
            <Image
              source={require('../assets/images/good_d_c1.jpg')}
              style={styles.cover}
            />
            <Price
              price="150"
              fontSize={28}
              signStyle={{ bottom: 4, fontSize: 14 }}
              fontWeight
            />
            <View style={[styles.priceWrap, flexCol.default]}>
              <Text style={styles.priceTxt}>实际付</Text>
              <Price
                price="132"
                fontSize={20}
                color="#ffffff"
                signStyle={{ bottom: 2, fontSize: 14 }}
                fontWeight
              />
            </View>
            <Pressable onPress={goBack} style={styles.close}>
              <Text style={styles.close}>&#xe617;</Text>
            </Pressable>
          </View>
          <Animated.View
            style={[
              styles.cardWrap,
              flexCol.default,
              styles.addressWrap,
              {
                borderRadius: borderRadius,
              },
            ]}
          >
            <Text style={styles.addressIcon}>&#xe611;</Text>
            <View style={styles.addressTxtWrap}>
              <Text style={styles.addressTxt} numberOfLines={1}>
                广东省广州市天河区车陂大马路二号菜鸟驿站二号店
              </Text>
              <Text style={{ color: '#666666' }}>
                包邮 运算费险 现货，付款48小时到货
              </Text>
            </View>
            <Text style={styles.addressArrow}>&#xe643;</Text>
          </Animated.View>
          <ScrollView
            style={styles.scrollContain}
            onScroll={Animated.event(
              [{ nativeEvent: { contentOffset: { y: scrollY } } }],
              { useNativeDriver: false },
            )}
            scrollEventThrottle={16}
          >
            <View style={[styles.cardWrap, { paddingBottom: 12 }]}>
              <Text style={styles.cardTit}>颜色分类</Text>
              <View style={styles.attrBox}>
                {attributes.map(item => (
                  <Pressable
                    onPress={() => onSetAttrs('attr', item.id)}
                    key={item.id}
                    style={styles.attrCnt}
                  >
                    <View
                      style={[
                        styles.attrMargin,
                        attrObj.attr === item.id && styles.attrMarginActive,
                      ]}
                    >
                      <Image style={styles.attrImg} source={item.cover} />
                      <Text
                        style={[
                          styles.attrTit,
                          attrObj.attr === item.id && styles.attrTitActive,
                        ]}
                      >
                        {item.tit}
                      </Text>
                    </View>
                  </Pressable>
                ))}
              </View>
              <Text style={styles.cardTit}>尺寸</Text>
              <View style={styles.attrBox}>
                {attributes2.map(item => (
                  <Pressable
                    onPress={() => onSetAttrs('attr2', item.id)}
                    key={item.id}
                    style={styles.attrCnt}
                  >
                    <View
                      style={[
                        styles.attrMargin,
                        attrObj.attr2 === item.id && styles.attrMarginActive,
                      ]}
                    >
                      <Text
                        style={[
                          styles.attrTit,
                          attrObj.attr2 === item.id && styles.attrTitActive,
                        ]}
                      >
                        {item.tit}
                      </Text>
                    </View>
                  </Pressable>
                ))}
              </View>
            </View>
            <GoodNum ref={goodNumRef} />
          </ScrollView>
          <SafeAreaView>
            <View style={flexCol(styles.footBtnWrap)}>
              <Pressable onPress={goCart} style={flexCol(styles.footBtn)}>
                <LinearGradient
                  colors={['#fbce6a', '#fed66f']}
                  style={flexCol(styles.footBtn)}
                  start={{ x: 0.2, y: 0.5 }}
                  end={{ x: 0.8, y: 0.5 }}
                >
                  <Text style={styles.footBtnTxt}>加入购物车</Text>
                </LinearGradient>
              </Pressable>
            </View>
          </SafeAreaView>
        </Pressable>
      </Animated.View>
    </Pressable>
  )
})
const GoodNum = forwardRef(function (_, ref) {
  const [num, setNum] = useState(1)
  const txtIptRef = useRef<TextInput>(null)
  useImperativeHandle(
    ref,
    () => ({
      getValue() {
        return num
      },
    }),
    [num],
  )
  function onChangeNum(newNum: number | string) {
    newNum = typeof newNum === 'string' ? parseInt(newNum, 10) : newNum
    newNum = isNaN(newNum) ? 1 : newNum
    setNum(newNum <= 0 ? 1 : newNum)
  }
  function onSubmitEditing() {
    onChangeNum(num)
    txtIptRef.current?.blur()
  }
  return (
    <View
      style={[
        styles.cardWrap,
        flexCol.default,
        { padding: 12, marginBottom: 12 },
      ]}
    >
      <Text style={[styles.countTit, { paddingBottom: 0 }]}>数量</Text>
      <View style={[flexCol.default, styles.numWrap]}>
        <Pressable onPress={() => onChangeNum(num - 1)}>
          <Text style={styles.txtBtn}>-</Text>
        </Pressable>
        <TextInput
          style={[styles.txtBtn, styles.txtNpt]}
          ref={txtIptRef}
          value={num + ''}
          onChangeText={txt => onChangeNum(txt)}
          keyboardType="number-pad"
          onSubmitEditing={onSubmitEditing}
        />
        <Pressable onPress={() => onChangeNum(num + 1)}>
          <Text style={styles.txtBtn}>+</Text>
        </Pressable>
      </View>
    </View>
  )
})
const styles = StyleSheet.create({
  goodParams: {
    width: '100%',
    height: '100%',
    backgroundColor: '#00000088',
  },
  priceWrap: {
    borderRadius: 14,
    height: 28,
    backgroundColor: '#ff2222',
    marginLeft: 8,
    paddingHorizontal: 8,
  },
  priceTxt: {
    color: '#fff',
    fontSize: 14,
  },
  bgm: {
    width: '100%',
    height: '100%',
    position: 'absolute',
    left: 0,
    top: 0,
  },
  container: {
    width: '100%',
    height: '80%',
    position: 'absolute',
    zIndex: 1,
    backgroundColor: '#f1f1f1',
    bottom: 0,
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
    left: 0,
    flexDirection: 'column',
  },
  header: {
    paddingTop: 12,
    width: '100%',
    position: 'relative',
    paddingHorizontal: 12,
  },
  close: {
    marginLeft: 'auto',
    alignSelf: 'flex-start',
    fontFamily: 'iconfont',
    fontSize: 20,
    color: '#333',
  },
  scrollContain: {
    flex: 1,
    width: '100%',

    paddingHorizontal: 12,
  },
  footBtnWrap: {
    width: '100%',
    paddingHorizontal: 12,
  },
  footBtn: {
    flex: 1,
    height: 44,
    borderRadius: 22,
    justifyContent: 'center',
  },
  footBtnTxt: {
    textAlign: 'center',
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  cover: {
    width: 68,
    height: 68,
    borderRadius: 8,
    backgroundColor: '#fff',
    marginRight: 12,
  },
  cardWrap: {
    backgroundColor: '#fff',
    borderRadius: 12,
    marginTop: 12,
  },
  addressWrap: {
    height: 72,
  },
  countTit: {
    fontSize: 16,
    color: '#333',
    fontWeight: 'bold',
    flex: 1,
  },
  addressIcon: {
    fontFamily: 'iconfont',
    fontSize: 16,
    color: '#666',
    marginHorizontal: 12,
  },
  addressTxtWrap: {
    flex: 1,
  },
  addressTxt: {
    fontWeight: 'bold',
    marginBottom: 8,
    color: '#333',
    fontSize: 16,
  },
  addressArrow: {
    marginRight: 12,
    color: '#666',
    marginLeft: 12,
    fontFamily: 'iconfont',
    fontSize: 16,
  },
  cardTit: {
    paddingTop: 12,
    color: '#333',
    fontSize: 16,
    paddingBottom: 10,
    paddingHorizontal: 12,
  },
  attrBox: {
    display: 'flex',
    flexWrap: 'wrap',
    flexDirection: 'row',
    marginLeft: 8,
    marginRight: 8,
  },
  attrCnt: {
    width: '33.3%',
  },
  attrImg: {
    width: '100%',
    height: 100,
    borderRadius: 4,
    resizeMode: 'cover',
    marginBottom: 6,
  },
  attrMargin: {
    margin: 4,
    borderColor: '#fff',
    borderWidth: 1,
    overflow: 'hidden',
    borderRadius: 4,
  },
  attrMarginActive: {
    borderColor: '#57aef0',
  },
  attrTit: {
    textAlign: 'center',
    padding: 2,
    width: '100%',
    backgroundColor: '#f1f1f1',
    height: 28,
    lineHeight: 24,
    borderRadius: 6,
  },
  attrTitActive: {
    color: '#57aef0',
    backgroundColor: '#57aef011',
  },
  countWrap: {
    padding: 12,
    marginBottom: 12,
  },
  numWrap: {
    borderWidth: 1,
    borderColor: '#e1e1e1',
    borderRadius: 4,
  },
  txtBtn: {
    width: 34,
    height: 34,
    textAlign: 'center',
    lineHeight: 32,
    color: '#333333',
    fontSize: 14,
  },
  txtNpt: {
    lineHeight: 18,
    backgroundColor: '#eee',
  },
  txtNum: {
    backgroundColor: '#eee',
  },
})
